﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Model.Customer;
using KingsSharp.Web.Mvc.Binders;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Contract.Logs;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Dto.Logs;
using CRM.Admin.Contracts.Model.Customer;
using CRM.Admin.Services.Service.Logs;
using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.UI;
using KingsSharp.Core.Data.Entity;
using CRM.Admin.Contracts.Contract.Sys;

namespace CRM.Admin.Areas.Customer.Controllers
{
    public class NatureController : Controller
    {
        /// <summary>
        /// 顾客性质业务契约
        /// </summary>
        public INatureService NatureService { get; set; }
        /// <summary>
        /// 用户业务契约
        /// </summary>
        public IUserInfoService UserInfoService { get; set; }

        /// <summary>
        /// 是否具备某个页面的权限
        /// </summary>
        /// <param name="actionName">页面名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="operaName">操作名称</param>
        /// <returns></returns>
        public bool Graent(string actionName, string controllerName, string operaName)
        {
            return UserInfoService.GetUserForPageGarent(actionName, controllerName, operaName, AppVariable.UserData.UserId);
        }
        #region 视图功能
        /// <summary>
        /// 性质列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureIndex()
        {
            var zTree = GetNatureCatalogData();
            ViewBag.createNaturegarent = Graent("NatureIndex", "Nature", "insert");
            ViewBag.updateNaturegarent = Graent("NatureIndex", "Nature", "update");
            ViewBag.deleteNaturegarent = Graent("NatureIndex", "Nature", "delete");
            return View((object)zTree.ToJsonString(true));
        }

        /// <summary>
        /// 新增性质类别
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureTypeAdd()
        {
            return View();
        }
        /// <summary>
        /// 编辑性质类别
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureTypeEdit(Guid CatalogId)
        {
            var model = NatureService.NatureCatalogs.FirstOrDefault(entity => entity.Id == CatalogId);
            return View(model);
        }
        /// <summary>
        /// 新增顾客性质详情
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureAdd()
        {
            return View();
        }
        /// <summary>
        /// 编辑顾客性质详情
        /// </summary>
        /// <param name="NatureId"></param>
        /// <returns></returns>
        public ActionResult NatureEdit(Guid NatureId)
        {
            var dto = NatureService.Natures.FirstOrDefault(a => a.Id == NatureId).MapTo<NatureDto>();
            return View(dto);
            //var dto = NatureService.Natures.Where(a => a.Id == NatureId).FirstOrDefault().MapTo<NatureDto>();
            //return View(dto);

        }

        /// <summary>
        /// 顾客性质选择
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureChecked()
        {
            var zTree = GetNatureCatalogData();
            return View((object)zTree.ToJsonString(true));
        }
        /// <summary>
        /// 获取性质目录菜单树
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureTypeTree()
        {
            var zTree = GetNatureCatalogData();
            return View((object)zTree.ToJsonString(true));
        }

        public ActionResult GetNatureTypeTree()
        {
            var zTree = GetNatureCatalogData();
            return Json(zTree.ToJsonString(true), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 数据功能

        /// <summary>
        /// 保存顾客性质类别数据
        /// </summary>
        /// <returns></returns>
        public ActionResult NatureTypeInsert([ModelBinder(typeof(JsonBinder<NatureCatalogDto>))] NatureCatalogDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = NatureService.Insert(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "顾客性质“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult NatureUpdate(NatureDto dto)
        {
            dto.CheckNotNull("dto");
            var result = NatureService.Update(dto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "性质“{0}”更新成功。".FormatWith(dto.Value);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        /// <summary>
        /// 保存顾客性质明细数据
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public ActionResult NatureInsert([ModelBinder(typeof(JsonBinder<NatureDto>))] NatureDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = NatureService.Insert(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "性质“{0}”添加成功。".FormatWith(dtos.Value);
            }
            return Json(new AjaxResult(msg, msgType));
        }

        public ActionResult NatureRemove(Guid[] deleteids)
        {
            deleteids.CheckNotNull("deleteids");
            var result = NatureService.Delete(true, deleteids);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();

            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult GetNatureGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<Nature, bool>> predicate = FilterHelper.GetExpression<Nature>(request.FilterGroup);
            int total;
            var data = NatureService.Natures.
                Where<Nature, Guid>(predicate, request.PageCondition, out total).
                Where(a => a.IsDeleted == false).
                Select(dto => new
                {
                    dto.Id,
                    dto.Value,
                    dto.IsDeleted,
                    dto.Order,
                    dto.Description,
                    NatureCatalogName = dto.NatureCatalog.Name,
                    NatureId = dto.Id
                }).ToList();
            return Json(new GridData<object>(data, total), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取顾客性质目录树
        /// </summary>
        /// <returns></returns>
        private ICollection<ZTreeNode> GetNatureCatalogData()
        {
            var data = NatureService.NatureCatalogs.Where(entity => entity.IsDeleted == false)
              .OrderByDescending(entity => entity.Order).ToList();
            var zTree = data.RenderTree(data.Where(node =>
                node.Parent == null).ToList(), (catalog, level) =>
                {
                    return new ZTreeNode()
                    {
                        Id = catalog.Id.ToString(),
                        Name = catalog.Name,
                        Order = catalog.Order,
                        obj = catalog.Multi,
                        Open = level < 3
                    };
                }, (catalog, sources) =>
                {
                    return sources.Where(a => a.Parent != null
                        && a.Parent.Id == catalog.Id).ToList();
                }, (parentNode, newNode) =>
                {
                    if (parentNode.Children == null)
                    {
                        parentNode.Children = new List<ZTreeNode>();
                    }
                    parentNode.Children.Add(newNode);
                });
            return zTree;
        }
        #endregion
    }
}